package com.example.demo.Calculate;

/**
 * @作者:邹蕴果
 * @创建时间：2021/7/19
 * @修改时间：2021/7/20
 */
    import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

    //CSV文件导出类
    public class CsvExportHandler<T extends CsvExportable> {

        //导出文件
        public void exportCsvFile(List<T> rowDataList,String csvFilePath)
                throws Exception{

            if (rowDataList.size() == 0) {
                throw new Exception("无导出数据.");
            }


            T rowDataObj = rowDataList.get(0);

            //将数据写入csv格式文件
            writeToCsv(rowDataList,rowDataObj,csvFilePath);
        }

       //写文件方法
        private void writeToCsv(List<T> dataList, T rowDataObj, String filePath) throws Exception {
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            String enter = "\r\n";
            String sLine;
            StringBuffer write ;
            fos = new FileOutputStream(new File(filePath));
            bos = new BufferedOutputStream(fos);
            write = new StringBuffer();
            bos.write(write.toString().getBytes("UTF-8"));
            for (int i = 0; i < dataList.size(); i++) {
                write = new StringBuffer();
                T rowData = dataList.get(i);
                //输出CSV格式的数据行
                sLine = rowData.outputCsvDataLine();
                //写数据行
                write.append(sLine);
                //加换行符
                write.append(enter);
                bos.write(write.toString().getBytes("UTF-8"));
            }
            //刷新数据
            bos.flush();

            //关闭流
            bos.close();
            fos.close();
        }
    }

